package top.jiangqiang.examples;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * 发送定时/延时消息
 */
@Slf4j
public class ProducerDelayMessageExample {

    public static void main(String[] args) throws ClientException, IOException {
        final ClientServiceProvider provider = ClientServiceProvider.loadService();

        String topic = "DelayTopic";
        final Producer producer = ProducerSingleton.getInstance(topic);
        String tag = "yourMessageTagA";
        final Message message = provider.newMessageBuilder()
                .setTopic(topic)
                .setTag(tag)
                // key
                .setKeys("yourMessageKey-3ee439f945d7")
                // 设置延时
                .setDeliveryTimestamp(System.currentTimeMillis() + Duration.ofSeconds(10).toMillis())
                .setBody("This is a delay message for Apache RocketMQ".getBytes(StandardCharsets.UTF_8))
                .build();
        try {
            final SendReceipt sendReceipt = producer.send(message);
            log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
        } catch (Throwable t) {
            log.error("Failed to send message", t);
        } finally {
            producer.close();
        }
    }
}